/**
 * Imported packages
 */
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;

/**
 *
 * @authors BENSON WACHIRA, DOROTHY SARPONG, STANLEY ANKU
 * MICHAEL ESHUN & MAKAFUI AMEZAH
 */

/**
 * 
 * Controller for add flight form
 */
public class ControllerAddFlight {
    
    /**
     * variable and objects declaration
     */
    Connection conn=null;
    String querry;
    Statement st=null;
    public EnterFlight addFlt; 
    private ActionListener actionListener;
    
    /**
     * constructor to instantiate objects declared
     */
    public ControllerAddFlight( ){
        addFlt = new EnterFlight();
        addFlt.setVisible(true);
                          
    }
    
    /**
     * Method to add flights
     */
    public void addFlights(){
    try{
       Class.forName("com.mysql.jdbc.Driver");
       conn =(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/jetwingdb?zeroDateTimeBehavior=convertToNull","root","");
       
        querry=("INSERT INTO Flights SET fName=?,fFrom=? ,destination =?,Price =?,fCapacity =?,depatureTime =?, arrivalTime=?;");
        
    PreparedStatement p =conn.prepareStatement(querry);
    p.setString(1, addFlt.getFName().getText());
    p.setString(2, addFlt.getFrom().getText());
    p.setString(3, addFlt.getDestination().getText());
    p.setString(4, addFlt.getCost().getText());
    p.setString(5, addFlt.getCapacity().getText());
    p.setString(6, addFlt.getDptTime().getText());
    p.setString(7, addFlt.getArrivalTime().getText());
    p.execute();
        
    p.close();
   conn.close();
  JOptionPane.showMessageDialog(null, "Flight has been succesfully added");
    }  
    catch(Exception e){
    JOptionPane.showMessageDialog(null,e);
    }
    
    }
    
    /**
     * Method to get source of button clicked using action listener
     */
     public void contol(){        
        actionListener = new ActionListener() {
              public void actionPerformed(ActionEvent actionEvent) {  
                  if(actionEvent.getSource()==addFlt.getSaveButton()){
                        addFlights();
                  }
                  if(actionEvent.getSource()==addFlt.getCloseButton()){
                  addFlt.setVisible(false);
                  
                  }
              }
              
        };                
        addFlt.getSaveButton().addActionListener(actionListener);
        addFlt.getCloseButton().addActionListener(actionListener);
    }
    
}
